#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <stdlib.h>
#define _SEM_CNT_ 5
static sem_t blank,xfull;
int queue[_SEM_CNT_];
int beginnum = 100;
void* producter(void* arg)
{
        int i = 0;
        while (1){
                sem_wait(&blank);//申请资源blank--
                printf("---%s---%lu---%d\n",__FUNCTION__,pthread_self(),beginnum);
                queue[(i++)%_SEM_CNT_] = beginnum++;
                sem_post(&xfull);//xfull++
                sleep(rand()%3);
        }
        return NULL;
}
void* customer(void* arg)
{
        int i = 0;
        int num = 0;
        while (1){
                sem_wait(&xfull);
                num = queue[(i++) % _SEM_CNT_];
                printf("---%s---%lu---%d\n",__FUNCTION__,pthread_self(),num);
                sem_post(&blank);
        }
        return NULL;
}
int main(int argc, char const *argv[])
{
        sem_init(&blank,0,_SEM_CNT_);
        sem_init(&xfull,0,0);//消费者一开始的初始化默认没有产品

        pthread_t tid[5];

        pthread_create(&tid[0],NULL,producter,NULL);
        pthread_create(&tid[1],NULL,producter,NULL);
        pthread_create(&tid[2],NULL,producter,NULL);
        pthread_create(&tid[3],NULL,customer,NULL);

        pthread_join(tid[0],NULL);
        pthread_join(tid[1],NULL);

        sem_destroy(&blank);
        sem_destroy(&xfull);

        pthread_exit(NULL);
        return 0;
}
